//
//  HomeVideoController.m
//  OnionHome
//
//  Created by fengjie on 2019/9/18.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "HomeVideoController.h"
#import "ShareViewController.h"
#import "HomeCommentsController.h"

#import "CLPlayerView.h"

@interface HomeVideoController ()<UITableViewDelegate, UITableViewDataSource, CLTableViewCellDelegate, UIScrollViewDelegate>
/**tableView*/
@property (nonatomic, strong) UITableView *tableView;
/**<#属性#>*/
@property (nonatomic,strong)NSMutableArray*dataSoure;

/**CLplayer*/
@property (nonatomic, weak) CLPlayerView *playerView;
/**记录Cell*/
@property (nonatomic, assign) UITableViewCell *cell;

@end

@implementation HomeVideoController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self pausePlay];
    DLogFunc;
}
#pragma mark UITableViewDelegate, UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSoure.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HomeVideoCell class]) forIndexPath:indexPath];
    
    cell.delegate = self;
    return cell;
}
#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    VideoDetailController * vc = [VideoDetailController new];
    vc.model = self.dataSoure[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}
//在willDisplayCell里面处理数据能优化tableview的滑动流畅性，cell将要出现的时候调用
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    HomeVideoCell * myCell = (HomeVideoCell *)cell;
    myCell.model = self.dataSoure[indexPath.row];
}
//cell离开tableView时调用
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //因为复用，同一个cell可能会走多次
    if ([_cell isEqual:cell]) {
        //区分是否是播放器所在cell,销毁时将指针置空
        [_playerView destroyPlayer];
        _cell = nil;
    }
}
#pragma mark - 点击播放代理
- (void)cl_tableViewCellPlayVideoWithCell:(HomeVideoCell *)cell{
    //记录被点击的Cell
    _cell = cell;
    //销毁播放器
    [_playerView destroyPlayer];
    CLPlayerView *playerView = [[CLPlayerView alloc] initWithFrame:CGRectZero];
    _playerView = playerView;
    [cell.playerBgView addSubview:_playerView];
    [playerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    //    //重复播放，默认不播放
    //    _playerView.repeatPlay = YES;
    //    //当前控制器是否支持旋转，当前页面支持旋转的时候需要设置，告知播放器
//        _playerView.isLandscape = YES;
    //    //设置等比例全屏拉伸，多余部分会被剪切
    //    _playerView.fillMode = ResizeAspectFill;
    //设置进度条背景颜色
    _playerView.progressBackgroundColor = [UIColor colorWithRed:53 / 255.0 green:53 / 255.0 blue:65 / 255.0 alpha:1];
    //设置进度条缓冲颜色
    _playerView.progressBufferColor = [UIColor grayColor];
    //设置进度条播放完成颜色
    _playerView.progressPlayFinishColor = UIColorFromRGB(0x009966);
    //    //全屏是否隐藏状态栏
//        _playerView.fullStatusBarHidden = NO;
    //    //转子颜色
    //    _playerView.strokeColor = [UIColor redColor];
    //视频地址
    _playerView.url = [NSURL URLWithString:cell.model.videoUrl];
    //播放
    [_playerView playVideo];
    //返回按钮点击事件回调
    [_playerView destroyPlay:^{
        cell.stopPlay = YES;
        DLog(@"播放器被销毁了");
    }];
    [_playerView backButton:^(UIButton *button) {
        DLog(@"返回按钮被点击");
    }];
    //播放完成回调
    kWeakSelf(weakSelf);
    [_playerView endPlay:^{
        //销毁播放器
        [weakSelf.playerView destroyPlayer];
        weakSelf.playerView = nil;
        weakSelf.cell = nil;
        DLog(@"播放完成");
    }];
}

/**暂停*/
- (void)pausePlay{
    [self.playerView pausePlay];
}
#pragma mark ---懒加载

/**tableView*/
- (UITableView *) tableView{
    if (_tableView == nil){
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.estimatedRowHeight = 44.0f;
        _tableView.separatorColor = SeparatorColor;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[HomeVideoCell class] forCellReuseIdentifier:NSStringFromClass([HomeVideoCell class])];
    }
    return _tableView;
}
-(NSMutableArray *)dataSoure{
    if (!_dataSoure) {
        _dataSoure = [[NSMutableArray alloc] init];
        NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Date" ofType:@"json"]];
        NSArray *array = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
        [array enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            PlayModel *model = [PlayModel new];
            [model setValuesForKeysWithDictionary:obj];
            model.userImage = [Utilis getRandomUserImage];
            [_dataSoure addObject:model];
        }];
    }
    return _dataSoure;
}
@end

#import "PlayBottomToolBar.h"


#pragma mark HomeVideoCell

@interface HomeVideoCell ()
/**播放视图父视图*/
@property (nonatomic,strong) UIImageView *IMGView;
/**播放次数*/
@property (nonatomic,strong)UILabel * leftLabel;
/**时间*/
@property (nonatomic,strong)UILabel * rightLabel;
/**播放按钮*/
@property (nonatomic,strong)UIButton * stopBtn;
/**<#属性#>*/
@property (nonatomic,strong)UIImageView * userImage;
@end

@implementation HomeVideoCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self createUI];
    }
    return self;
}
-(void)createUI{
    UIView * maskeView = UIView.new;
    maskeView.backgroundColor = RGBA(39, 51, 35, 0.3);
    maskeView.userInteractionEnabled = YES;
    
    self.IMGView = UIImageView.new;
    self.IMGView.userInteractionEnabled = YES;
    
    self.playerBgView = UIView.new;
    self.playerBgView.userInteractionEnabled = YES;
    self.playerBgView.hidden = YES;
    
    [self addSubview:self.IMGView];
    [self addSubview:self.playerBgView];
    
    UILabel * titleLabel = UILabel.new;
    titleLabel.textColor = UIColorFromRGB(0xFFFFFF);
    titleLabel.font = PingFangSC_Medium(16);
    titleLabel.text = @"这个夏天一定要瘦，减脂沙拉了解一下~";

    self.leftLabel = UILabel.new;
    self.leftLabel.textColor = UIColorFromRGB(0xF5F7F5);
    self.leftLabel.font = PingFangSC_Medium(11);
    self.leftLabel.text = @"12万次播放";
    
    self.rightLabel = UILabel.new;
    self.rightLabel.textColor = UIColorFromRGB(0xF5F7F5);
    self.rightLabel.font = PingFangSC_Medium(11);
    self.rightLabel.text = @"05:19";

    self.stopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.stopBtn setBackgroundImage:IMAGE_NAMED(@"video_play") forState:UIControlStateNormal];
    kWeakSelf(weakSelf);
    [self.stopBtn addActionHandler:^{
        weakSelf.playerBgView.hidden = NO;
        [weakSelf playAction];
    }];
    
    [self.IMGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(210);
    }];
    
    [self.playerBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.bottom.mas_equalTo(self.IMGView);
    }];
    
    [self.IMGView addSubview:maskeView];
    
    [maskeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    [maskeView addSubview:titleLabel];
    [maskeView addSubview:self.stopBtn];
    [maskeView addSubview:self.leftLabel];
    [maskeView addSubview:self.rightLabel];

    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(16);
        make.right.mas_equalTo(-16);
    }];
    
    [self.stopBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
    }];
    [self.leftLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(16);
        make.bottom.mas_equalTo(-16);
    }];
    [self.rightLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.mas_equalTo(-16);
    }];
        
    UIView * view = [self createBottomView];
    [self addSubview:view];
    
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.IMGView.mas_bottom).offset(16);
        make.left.mas_equalTo(16);
        make.bottom.right.mas_equalTo(-16);
    }];

    
}

/// 进入用户个人中心页面
-(void)pushUserContenPage{
    PersonalHomePageBasseController * vc = [[PersonalHomePageBasseController alloc] init];
    vc.type = PersonalHomePageTA;
    [[self getCurrentViewController].navigationController pushViewController:vc animated:YES];
}

-(UIView *)createBottomView{
    UIView * view = UIView.new;
    
    self.userImage = UIImageView.new;
    self.userImage.image = IMAGE_NAMED(@"userIconDefut");
    self.userImage.layer.cornerRadius = 20;
    self.userImage.layer.masksToBounds = YES;
    self.userImage.userInteractionEnabled = YES;
    
    [self.userImage addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pushUserContenPage)]];
    
    UILabel * userName = UILabel.new;
    userName.textColor = UIColorFromRGB(0x273323);
    userName.font = PingFangSC_Medium(14);
    userName.text = @"我是大鲨鱼";
    
    userName.userInteractionEnabled = YES;
    
    [userName addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pushUserContenPage)]];

    
    UIButton * guanzhuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [guanzhuBtn setTitleColor:UIColorFromRGB(0xFF7300) forState:UIControlStateNormal];
    [guanzhuBtn setTitle:@"关注" forState:UIControlStateNormal];
    guanzhuBtn.titleLabel.font = PingFangSC_Medium(14);
    
    UIButton * measgBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [measgBtn setTitleColor:UIColorFromRGB(0x959E97) forState:UIControlStateNormal];
    [measgBtn setTitle:@"300" forState:UIControlStateNormal];
    measgBtn.titleLabel.font = SYSTEMFONT(12);
    [measgBtn setImage:IMAGE_NAMED(@"home_mesae") forState:UIControlStateNormal];
    [measgBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 4, 0, -4)];
    
    kWeakSelf(weakSelf);
    [measgBtn addActionHandler:^{
        PresentationObject * objcet = [PresentationObject sharedPresentationObject];
        objcet.subViewFrame = CGRectMake(0, 225, KScreenWidth, KScreenHeight - 225);
        [objcet showPresentingViewController:[weakSelf getCurrentViewController] PresentedViewController:[HomeCommentsController new]];
    }];

    
    UIButton * sangedianBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sangedianBtn setBackgroundImage:IMAGE_NAMED(@"sangedian") forState:UIControlStateNormal];
    
    [sangedianBtn addActionHandler:^{
        PresentationObject * object = [PresentationObject sharedPresentationObject];
        object.subViewFrame = CGRectZero;
        [object showPresentingViewController:[weakSelf getCurrentViewController] PresentedViewController:[[BasseNavigationController alloc]initWithRootViewController:[ShareViewController new]]];

    }];

    
    [view addSubview:self.userImage];
    [view addSubview:userName];
    [view addSubview:guanzhuBtn];
    [view addSubview:measgBtn];
    [view addSubview:sangedianBtn];

    [self.userImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(0);
        make.width.height.mas_equalTo(40);
    }];
    
    [userName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(self.userImage.mas_right).offset(8);
    }];
    [guanzhuBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.left.mas_equalTo(userName.mas_right).offset(10);
    }];

    [measgBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.right.mas_equalTo(sangedianBtn.mas_left).offset(-10);
    }];
    [sangedianBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(0);
        make.right.mas_equalTo(0);
    }];

    
    return view;
}

-(void)setModel:(PlayModel *)model{
    _model = model;
    self.userImage.image = model.userImage;
    [self.IMGView imageViewWithUrl:model.pictureUrl placeholderImage:@"dynamicDefut"];
}
-(void)setSelected:(BOOL)selected animated:(BOOL)animated{
    [super setSelected:selected animated:animated];
}
- (void)setStopPlay:(BOOL)stopPlay
{
    _stopPlay = stopPlay;
    self.playerBgView.hidden = stopPlay;
}
- (void)playAction {
    
    if (_delegate && [_delegate respondsToSelector:@selector(cl_tableViewCellPlayVideoWithCell:)]){
        [_delegate cl_tableViewCellPlayVideoWithCell:self];
    }
}

@end
